import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { getCourseById, addStudentsToCourse, getCourseStudents, removeStudentFromCourse } from '@/services/course';
import { getStudentsByClass, getClasses, createStudent, getStudentsByClassID } from '@/services/class';
import { createSignInTask, getSignInTasks, manualSignIn, getSignInRecords, endSignInTask } from '@/services/signIn';
import { getStudentList } from '@/services/student';
import { Course, Student, SignInTask } from '@/types';
import '@/styles/pages/courseDetail.scss';

const CourseDetail = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [course, setCourse] = useState<Course | null>(null);
  const [students, setStudents] = useState<Student[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [isCreatingTask, setIsCreatingTask] = useState(false);
  const [taskDescription, setTaskDescription] = useState('');
  
  // 添加学生相关状态
  const [showAddStudentModal, setShowAddStudentModal] = useState(false);
  const [newStudentId, setNewStudentId] = useState('');
  const [isSearchingStudent, setIsSearchingStudent] = useState(false);
  const [createStudentError, setCreateStudentError] = useState('');
  const [classId, setClassId] = useState<number | null>(null);

  // 添加签到时间选择状态
  const [showSignInModal, setShowSignInModal] = useState(false);
  const [signInStartTime, setSignInStartTime] = useState('');
  const [signInEndTime, setSignInEndTime] = useState('');

  // 签到任务和签到相关状态
  const [activeTask, setActiveTask] = useState<SignInTask | null>(null);
  const [isSigningIn, setIsSigningIn] = useState(false);
  const [signInSuccess, setSignInSuccess] = useState('');
  const [signedStudents, setSignedStudents] = useState<Record<string, boolean>>({});
  // 添加结束签到任务的状态
  const [isEndingTask, setIsEndingTask] = useState(false);

  // 添加班级学生列表相关状态
  const [classStudents, setClassStudents] = useState<Student[]>([]);
  const [classStudentsLoading, setClassStudentsLoading] = useState(false);
  const [classStudentsError, setClassStudentsError] = useState('');
  const [className, setClassName] = useState('');

  useEffect(() => {
    if (id) {
      fetchCourseDetails(parseInt(id));
    }
  }, [id]);

  // 初始化签到时间
  useEffect(() => {
    // 设置默认开始时间为当前时间
    const now = new Date();
    // 格式化为 yyyy-MM-ddThh:mm 格式，适用于 datetime-local 输入
    const formatDatetimeLocal = (date: Date) => {
      // 获取本地时区的年月日时分
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      
      return `${year}-${month}-${day}T${hours}:${minutes}`;
    };
    
    setSignInStartTime(formatDatetimeLocal(now));
    
    // 设置默认结束时间为30分钟后
    const endTime = new Date(now.getTime() + 30 * 60000);
    setSignInEndTime(formatDatetimeLocal(endTime));
  }, []);

  // 获取当前课程的最新签到任务
  const fetchLatestSignInTask = async () => {
    if (!id) return;
    
    try {
      const res = await getSignInTasks(parseInt(id));
      console.log('获取课程签到任务:', res);
      
      if (res.code === 0 || res.code === 2000) {
        const tasks = res.data?.tasks || [];
        // 查找活跃状态的签到任务
        const activeTasks = tasks.filter(task => task.status === 'active');
        if (activeTasks.length > 0) {
          const currentTask = activeTasks[0]; // 设置最新的活跃任务
          setActiveTask(currentTask);
          
          // 获取签到记录
          try {
            const recordsRes = await getSignInRecords(currentTask.id);
            console.log('获取签到记录:', recordsRes);
            
            if (recordsRes.code === 0 || recordsRes.code === 2000) {
              const records = recordsRes.data?.records || [];
              
              // 创建已签到学生的映射
              const signedMap: Record<string, boolean> = {};
              records.forEach(record => {
                if (record.status === 'signed') {
                  signedMap[record.student_id] = true;
                }
              });
              
              setSignedStudents(signedMap);
              console.log('已签到学生:', signedMap);
            }
          } catch (err) {
            console.error('获取签到记录失败:', err);
          }
        } else {
          setActiveTask(null);
          setSignedStudents({});
        }
      }
    } catch (err) {
      console.error('获取签到任务失败:', err);
    }
  };

  const fetchCourseDetails = async (courseId: number) => {
    try {
      setLoading(true);
      setError('');
      
      const res = await getCourseById(courseId);
      console.log('课程详情响应:', res);
      
      if (res.code === 0 || res.code === 2000) {
        if (res.data) {
          setCourse(res.data);
          
          // 尝试获取课程关联的学生
          fetchCourseStudents(courseId);
          
          // 如果课程有关联班级，设置classId
          if (res.data.class_ids && res.data.class_ids.length > 0) {
            setClassId(res.data.class_ids[0]);
          } else {
            // 如果没有class_ids，则可能是老数据，使用字符串"计科223"从class表中查找对应的班级ID
            // 这里暂时硬编码为1，实际项目中应该从数据库查询
            setClassId(1);
          }
          
          // 获取最新签到任务
          fetchLatestSignInTask();
        } else {
          setError('未找到课程数据');
        }
      } else {
        setError(res.msg || '获取课程详情失败');
      }
    } catch (err: any) {
      console.error('获取课程详情出错:', err);
      setError(err.message || '网络错误，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  const fetchClasses = async () => {
    try {
      const res = await getClasses();
      if (res.code === 0 || res.code === 2000) {
        setClasses(res.data?.classes || []);
      }
    } catch (err) {
      console.error('获取班级列表失败:', err);
    }
  };

  const fetchCourseStudents = async (courseId: number) => {
    try {
      console.log('获取课程学生, courseId:', courseId);
      const res = await getCourseStudents(courseId);
      console.log('获取课程学生响应:', res);
      
      if (res.code === 0 || res.code === 2000) {
        if (res.data && Array.isArray(res.data.students)) {
          setStudents(res.data.students);
          console.log('设置学生列表:', res.data.students);
        } else {
          console.warn('学生数据格式不正确:', res.data);
          setStudents([]);
        }
      } else {
        console.error('获取课程学生失败:', res.message);
        // 如果获取课程学生失败，尝试获取班级学生
        if (course?.class_ids && course.class_ids.length > 0) {
          fetchStudents(course.class_ids[0]);
        }
      }
    } catch (err: any) {
      console.error('获取课程学生出错:', err);
      // 如果获取课程学生出错，尝试获取班级学生
      if (course?.class_ids && course.class_ids.length > 0) {
        fetchStudents(course.class_ids[0]);
      }
    }
  };

  const fetchStudents = async (classId: number) => {
    try {
      const res = await getStudentsByClass(classId);
      
      if (res.code === 0 || res.code === 2000) {
        setStudents(res.data?.students || []);
      }
    } catch (err: any) {
      console.error('获取学生列表出错:', err);
    }
  };

  const handleBackToList = () => {
    navigate('/courses');
  };

  // 修改为打开签到对话框
  const handleOpenSignInModal = () => {
    setShowSignInModal(true);
  };

  // 手动为学生签到
  const handleManualSignIn = async (studentId: string) => {
    if (!activeTask) {
      setError('当前没有进行中的签到任务');
      return;
    }
    
    try {
      setIsSigningIn(true);
      setError('');
      setSignInSuccess('');
      
      // 标记当前处理中的学生
      const processingStudentId = studentId;
      
      const res = await manualSignIn(activeTask.id, studentId);
      if (res.code === 0 || res.code === 2000) {
        setSignInSuccess(`学生 ${studentId} 签到成功`);
        
        // 更新已签到学生列表
        setSignedStudents(prev => ({
          ...prev,
          [studentId]: true
        }));
        
        // 重新获取签到记录以确保数据最新
        if (activeTask) {
          try {
            const recordsRes = await getSignInRecords(activeTask.id);
            if (recordsRes.code === 0 || recordsRes.code === 2000) {
              const records = recordsRes.data?.records || [];
              
              // 创建已签到学生的映射
              const signedMap: Record<string, boolean> = {};
              records.forEach(record => {
                if (record.status === 'signed') {
                  signedMap[record.student_id] = true;
                }
              });
              
              setSignedStudents(signedMap);
            }
          } catch (err) {
            console.error('获取签到记录失败:', err);
          }
        }
        
        // 延迟清除成功消息
        setTimeout(() => {
          setSignInSuccess('');
        }, 3000);
      } else {
        setError(res.message || '签到失败');
      }
    } catch (err: any) {
      console.error('手动签到出错:', err);
      setError(err.message || '网络错误，请稍后重试');
    } finally {
      setIsSigningIn(false);
    }
  };

  // 添加结束签到任务的处理函数
  const handleEndSignInTask = async () => {
    if (!activeTask) {
      setError('当前没有进行中的签到任务');
      return;
    }
    
    // 确认是否结束签到
    if (!window.confirm('确定要结束此签到任务吗？结束后将无法继续签到。')) {
      return;
    }
    
    try {
      setIsEndingTask(true);
      setError('');
      
      const res = await endSignInTask(activeTask.id);
      
      if (res.code === 0 || res.code === 2000) {
        setSignInSuccess('签到任务已结束');
        
        // 刷新签到任务状态
        fetchLatestSignInTask();
        
        // 延迟清除成功消息
        setTimeout(() => {
          setSignInSuccess('');
        }, 3000);
      } else {
        setError(res.message || '结束签到任务失败');
      }
    } catch (err: any) {
      console.error('结束签到任务出错:', err);
      setError(err.message || '网络错误，请稍后重试');
    } finally {
      setIsEndingTask(false);
    }
  };

  // 判断学生是否已签到
  const isStudentSigned = (studentId: string) => {
    return signedStudents[studentId] === true;
  };

  // 处理创建签到任务后的操作
  const handleCreateSignInTask = async () => {
    if (!course) return;
    
    // 验证时间输入
    if (!signInStartTime || !signInEndTime) {
      alert('请选择签到开始和结束时间');
      return;
    }
    
    // 将datetime-local输入转换为后端所需的格式 "2006-01-02 15:04:05"
    const formatTimeForBackend = (dateTimeString: string) => {
      // 解析datetime-local输入值
      const date = new Date(dateTimeString);
      
      // 获取本地时区的年月日时分秒
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = '00'; // 固定秒数为00
      
      // 使用本地时区格式化时间
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    };
    
    const startTimeFormatted = formatTimeForBackend(signInStartTime);
    const endTimeFormatted = formatTimeForBackend(signInEndTime);
    
    console.log('原始时间格式:', { signInStartTime, signInEndTime });
    console.log('转换后时间格式:', { startTimeFormatted, endTimeFormatted });
    
    try {
      setIsCreatingTask(true);
      
      // 使用课程关联的班级
      const classIds = course.class_ids || [];
      
      console.log('发送签到请求参数:', {
        courseId: course.id,
        classIds, 
        startTime: startTimeFormatted,
        endTime: endTimeFormatted,
        description: taskDescription || '课堂签到'
      });
      
      const res = await createSignInTask(
        course.id,
        classIds,
        startTimeFormatted,
        endTimeFormatted,
        taskDescription || '课堂签到'
      );
      
      console.log('创建签到任务响应:', res);
      
      if (res.code === 0 || res.code === 2000) {
        // 关闭对话框
        setShowSignInModal(false);
        
        // 清空任务描述
        setTaskDescription('');
        
        // 获取最新创建的签到任务
        fetchLatestSignInTask();
        
        // 显示成功消息
        setSignInSuccess('签到任务创建成功');
        
        // 延迟清除成功消息
        setTimeout(() => {
          setSignInSuccess('');
        }, 3000);
      } else {
        setError(res.msg || '创建签到任务失败');
        console.error('创建签到任务失败:', res);
      }
    } catch (err: any) {
      console.error('创建签到任务出错:', err);
      setError(err.message || '网络错误，请稍后重试');
    } finally {
      setIsCreatingTask(false);
    }
  };

  // 通过学号查询学生信息并添加到课程
  const handleSearchAndAddStudent = async () => {
    if (!course) return;
    
    if (!newStudentId.trim()) {
      setCreateStudentError('请输入学号');
      return;
    }
    
    setIsSearchingStudent(true);
    setCreateStudentError('');
    
    try {
      // 查询学生是否已存在
      const res = await getStudentList(classId || 1);
      console.log('查询学生响应:', res);
      
      if (res.code === 0 || res.code === 2000) {
        if (res.data && Array.isArray(res.data.students)) {
          // 查找匹配学号的学生
          const foundStudent = res.data.students.find(s => s.student_id === newStudentId);
          
          if (foundStudent) {
            // 添加该学生到课程
            const addRes = await addStudentsToCourse(course.id, [foundStudent.id]);
            
            if (addRes.code === 0 || addRes.code === 2000) {
              // 成功后关闭模态框并刷新
              setShowAddStudentModal(false);
              setNewStudentId('');
              
              // 显示成功消息
              alert('成功添加学生到课程');
              
              // 重新获取课程学生
              fetchCourseStudents(course.id);
            } else {
              setCreateStudentError('添加学生到课程失败: ' + (addRes.message || '未知错误'));
            }
          } else {
            setCreateStudentError('未找到该学号的学生，请确认学号是否正确');
          }
        } else {
          setCreateStudentError('学生数据格式不正确');
        }
      } else {
        setCreateStudentError(res.message || '查询学生失败');
      }
    } catch (err: any) {
      console.error('查询学生出错:', err);
      setCreateStudentError(err.message || '网络错误，请稍后重试');
    } finally {
      setIsSearchingStudent(false);
    }
  };

  // 从课程中移除学生
  const handleRemoveStudent = async (studentId: number) => {
    if (!course) return;
    
    if (!window.confirm('确定要将该学生从课程中移除吗？')) {
      return;
    }
    
    try {
      const res = await removeStudentFromCourse(course.id, studentId);
      
      if (res.code === 0 || res.code === 2000) {
        // 从学生列表中移除该学生
        setStudents(prev => prev.filter(s => s.id !== studentId));
      } else {
        setError(res.message || '移除学生失败');
      }
    } catch (err: any) {
      console.error('移除学生出错:', err);
      setError(err.message || '网络错误，请稍后重试');
    }
  };

  // 将Unix时间戳转换为格式化的日期时间字符串
  const formatTimestamp = (timestamp: number | string): string => {
    if (!timestamp) return '-';
    
    // 如果是字符串且包含常规格式的日期，则直接返回
    if (typeof timestamp === 'string' && timestamp.includes('-')) {
      return timestamp;
    }
    
    try {
      // 将时间戳转换为毫秒（如果是秒级时间戳）
      const ts = typeof timestamp === 'string' 
        ? parseInt(timestamp) 
        : timestamp;
        
      const milliseconds = ts > 10000000000 ? ts : ts * 1000;
      
      // 创建日期对象
      const date = new Date(milliseconds);
      
      // 使用本地时区格式化时间
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    } catch (error) {
      console.error('时间格式化错误:', error);
      return String(timestamp);
    }
  };

  // 添加获取班级学生的函数
  const fetchClassStudents = async () => {
    if (!course || !course.class_ids || course.class_ids.length === 0) {
      setClassStudentsError('课程未关联班级');
      return;
    }
    
    try {
      setClassStudentsLoading(true);
      setClassStudentsError('');
      
      const classId = course.class_ids[0]; // 获取第一个关联的班级ID
      const res = await getStudentsByClassID(classId);
      
      if (res.code === 0 || res.code === 2000) {
        if (res.data) {
          setClassStudents(res.data.students || []);
          setClassName(res.data.class_name || '未知班级');
        } else {
          setClassStudentsError('未找到班级学生数据');
          setClassStudents([]);
        }
      } else {
        setClassStudentsError(res.message || '获取班级学生失败');
        setClassStudents([]);
      }
    } catch (err: any) {
      console.error('获取班级学生出错:', err);
      setClassStudentsError(err.message || '网络错误，请稍后重试');
      setClassStudents([]);
    } finally {
      setClassStudentsLoading(false);
    }
  };

  // 在课程详情加载完成后获取班级学生
  useEffect(() => {
    if (course && course.class_ids && course.class_ids.length > 0) {
      fetchClassStudents();
    }
  }, [course]);

  // 添加将学生添加到课程的函数
  const handleAddStudentToCourse = async (studentId: number) => {
    if (!id) return;
    
    try {
      const courseId = parseInt(id);
      const res = await addStudentsToCourse(courseId, [studentId]);
      
      if (res.code === 0 || res.code === 2000) {
        // 添加成功后重新获取课程学生列表
        fetchCourseStudents(courseId);
        alert('学生添加成功');
      } else {
        alert(res.message || '添加学生失败');
      }
    } catch (err: any) {
      console.error('添加学生到课程出错:', err);
      alert(err.message || '网络错误，请稍后重试');
    }
  };

  if (loading) {
    return <div className="loading">加载中...</div>;
  }

  if (error) {
    return <div className="error-message">{error}</div>;
  }

  if (!course) {
    return <div className="not-found">未找到课程</div>;
  }

  return (
    <div className="course-detail-container">
      <div className="page-header">
        <button className="btn btn-default" onClick={handleBackToList}>
          返回课程列表
        </button>
        <h1>{course.name}</h1>
      </div>

      <div className="course-info">
        <div className="info-group">
          <label>课程名称:</label>
          <span>{course.name}</span>
        </div>
        <div className="info-group">
          <label>班级名称:</label>
          <span>{course.class_name}</span>
        </div>
        <div className="info-group">
          <label>课程描述:</label>
          <p>{course.description || '暂无描述'}</p>
        </div>
        <div className="info-group">
          <label>创建时间:</label>
          <span>{course.created_at ? new Date(course.created_at).toLocaleString() : '-'}</span>
        </div>
      </div>

      {error && <div className="error-message">{error}</div>}
      {signInSuccess && <div className="success-message">{signInSuccess}</div>}

      <div className="action-group">
        <h3>课程操作</h3>
        <div className="action-buttons">
          <button 
            className="btn btn-primary" 
            onClick={handleOpenSignInModal}
            disabled={isCreatingTask || !!activeTask}
          >
            {isCreatingTask ? '创建中...' : activeTask ? '已有进行中的签到' : '发起签到'}
          </button>
          <input
            type="text"
            placeholder="签到描述（选填）"
            value={taskDescription}
            onChange={(e) => setTaskDescription(e.target.value)}
            disabled={isCreatingTask}
          />
        </div>
      </div>

      {/* 活动签到任务信息 */}
      {activeTask && (
        <div className="active-task-section">
          <h3>当前签到任务</h3>
          <div className="task-detail-card">
            <div className="task-info">
              <div className="info-row">
                <span className="label">任务ID:</span>
                <span className="value">{activeTask.id}</span>
              </div>
              <div className="info-row">
                <span className="label">描述:</span>
                <span className="value">{activeTask.course_name}</span>
              </div>
              <div className="info-row">
                <span className="label">开始时间:</span>
                <span className="value time-value">{formatTimestamp(activeTask.start_time)}</span>
              </div>
              <div className="info-row">
                <span className="label">结束时间:</span>
                <span className="value time-value">{formatTimestamp(activeTask.end_time)}</span>
              </div>
              <div className="info-row">
                <span className="label">状态:</span>
                <span className={`status ${activeTask.status}`}>
                  {activeTask.status === 'active' ? '进行中' : '已结束'}
                </span>
              </div>
            </div>
            {/* 添加结束签到按钮 */}
            {activeTask.status === 'active' && (
              <div className="task-actions">
                <button 
                  className="btn btn-danger"
                  onClick={handleEndSignInTask}
                  disabled={isEndingTask}
                >
                  {isEndingTask ? '结束中...' : '结束签到'}
                </button>
              </div>
            )}
          </div>
        </div>
      )}

      <div className="students-section">
        <div className="section-header">
          <h3>课程学生列表{activeTask && ' (可进行手动签到)'}</h3>
          <button 
            className="btn btn-primary"
            onClick={() => setShowAddStudentModal(true)}
          >
            添加学生
          </button>
        </div>
        
        {students.length > 0 ? (
          <table className="student-table">
            <thead>
              <tr>
                <th>学号</th>
                <th>姓名</th>
                <th>备注</th>
                <th>操作</th>
                {activeTask && <th>签到状态</th>}
              </tr>
            </thead>
            <tbody>
              {students.map((student) => (
                <tr key={student.id}>
                  <td>{student.student_id}</td>
                  <td>{student.name}</td>
                  <td>{student.remark || '-'}</td>
                  <td>
                    <button 
                      className="btn btn-danger btn-sm"
                      onClick={() => handleRemoveStudent(student.id)}
                    >
                      移除
                    </button>
                  </td>
                  {activeTask && (
                    <td>
                      {isStudentSigned(student.student_id) ? (
                        <span className="sign-in-status signed">已签到</span>
                      ) : (
                        <button 
                          className="btn btn-sign-in btn-sm"
                          onClick={() => handleManualSignIn(student.student_id)}
                          disabled={isSigningIn}
                        >
                          手动签到
                        </button>
                      )}
                    </td>
                  )}
                </tr>
              ))}
            </tbody>
          </table>
        ) : (
          <div className="empty-tip">暂无学生数据</div>
        )}
      </div>

      {/* 添加签到时间选择对话框 */}
      {showSignInModal && (
        <div className="modal-overlay">
          <div className="modal">
            <div className="modal-header">
              <h3>发起签到</h3>
              <button 
                className="close-btn"
                onClick={() => setShowSignInModal(false)}
              >
                &times;
              </button>
            </div>
            
            <div className="modal-body">
              <div className="form-group">
                <label htmlFor="taskDescription">签到描述：</label>
                <input
                  id="taskDescription"
                  type="text"
                  value={taskDescription}
                  onChange={(e) => setTaskDescription(e.target.value)}
                  placeholder="请输入签到描述（选填）"
                />
              </div>
              
              <div className="form-group">
                <label htmlFor="startTime">开始时间：</label>
                <input
                  id="startTime"
                  type="datetime-local"
                  value={signInStartTime}
                  onChange={(e) => setSignInStartTime(e.target.value)}
                  required
                />
              </div>
              
              <div className="form-group">
                <label htmlFor="endTime">结束时间：</label>
                <input
                  id="endTime"
                  type="datetime-local"
                  value={signInEndTime}
                  onChange={(e) => setSignInEndTime(e.target.value)}
                  required
                />
              </div>
            </div>
            
            <div className="modal-footer">
              <button 
                className="btn btn-default"
                onClick={() => setShowSignInModal(false)}
              >
                取消
              </button>
              
              <button 
                className="btn btn-primary"
                onClick={handleCreateSignInTask}
                disabled={isCreatingTask}
              >
                {isCreatingTask ? '创建中...' : '确认发起'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 添加学生模态框 */}
      {showAddStudentModal && (
        <div className="modal-overlay">
          <div className="modal">
            <div className="modal-header">
              <h3>添加学生到课程</h3>
              <button 
                className="close-btn"
                onClick={() => setShowAddStudentModal(false)}
              >
                &times;
              </button>
            </div>
            
            <div className="modal-body">
              <div className="create-student-form">
                {createStudentError && <div className="error-message">{createStudentError}</div>}
                
                <div className="form-group">
                  <label htmlFor="newStudentId">学号：</label>
                  <div className="search-student-wrapper">
                    <input
                      id="newStudentId"
                      type="text"
                      value={newStudentId}
                      onChange={(e) => setNewStudentId(e.target.value)}
                      placeholder="请输入学生学号"
                      required
                    />
                  </div>
                </div>
              </div>
            </div>
            
            <div className="modal-footer">
              <button 
                className="btn btn-default"
                onClick={() => setShowAddStudentModal(false)}
              >
                取消
              </button>
              
              <button 
                className="btn btn-primary"
                onClick={handleSearchAndAddStudent}
                disabled={!newStudentId.trim() || isSearchingStudent}
              >
                {isSearchingStudent ? '查询中...' : '添加学生'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 添加班级学生列表部分 */}
      <div className="section class-students-section">
        <div className="section-header">
          <h2>班级学生列表 ({className})</h2>
          <button 
            className="btn btn-primary"
            onClick={fetchClassStudents}
          >
            刷新学生列表
          </button>
        </div>
        
        {classStudentsLoading ? (
          <div className="loading">加载班级学生中...</div>
        ) : classStudentsError ? (
          <div className="error-message">{classStudentsError}</div>
        ) : classStudents.length > 0 ? (
          <div className="student-list">
            <table>
              <thead>
                <tr>
                  <th>学号</th>
                  <th>姓名</th>
                  <th>人脸信息</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                {classStudents.map((student) => (
                  <tr key={student.id}>
                    <td>{student.student_id}</td>
                    <td>{student.name}</td>
                    <td>{student.has_face ? '已录入' : '未录入'}</td>
                    <td>
                      <button 
                        className="btn btn-small btn-primary"
                        onClick={() => handleAddStudentToCourse(student.id)}
                      >
                        添加到课程
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <div className="empty-data">该班级暂无学生数据</div>
        )}
      </div>
    </div>
  );
};

export default CourseDetail; 